<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" style="display:flex;align-items: center;justify-content: space-between;">
        <span>首页轮播图配置</span>
        <el-button icon="el-icon-plus" size="small" @click="handleAdd" type="success">添加配置</el-button>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableBanners" style="width: 100%">
          <el-table-column prop="order" label="序号" width="100"></el-table-column>
          <el-table-column prop="bannerPic" label="图片" width="180">
            <template slot-scope="scope">
              <el-image style="width:20%" :src="scope.row.bannerPic" :preview-src-list="[scope.row.bannerPic]"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="已关联商品"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="handleEdit($event,scope.row)" size="small">编辑</el-button>
              <el-button @click="handleDel($event,scope.row)" type="danger" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 弹窗提示 -->
    <el-dialog width="50%" :show-close="false" :destroy-on-close="true" :title=" ifEdit? '编辑' : '新增' " :visible.sync="dialogShow">
      <el-form :model="form" :inline="false" ref="ruleForm">
        <!-- 用户可以选择是需要静态banner还是别的什么 -->
        <el-form-item :label-width="'100px'" label="是否关联商品">
          <el-switch v-model="ifNeedGoodsLink"></el-switch>
          <br>
          <el-select style="width:75%;marginTop:20px" :disabled="!ifNeedGoodsLink" v-model="needGoodsId" filterable remote clearable reserve-keyword placeholder="请输入您要关联的商品名称(支持模糊查询)" :remote-method="remoteMethod" :loading="selectLoading">
            <el-option v-for="item in selectSearchOptions" :key="item.productId" :label="item.productName" :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 图片上传组件 -->
        <el-form-item required :label-width="'100px'" label="上传轮播图">
          <div style="display:flex">
            <!-- 图片上传组件 -->
            <UploadImage ref="UploadImage" :defaultList.sync="bannerList" color="#1890ff" @delCallBack="imageSuccess" @successCBK="imageSuccess" class="editor-upload-btn" />
            <!-- tips -->
            <i style="color: #909399;margin-left:20px">建议上传尺寸: 790×247</i>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialog">取 消</el-button>
        <el-button @click="handleAddBanner" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage/UploadImage';
export default {
  data() {
    return {
      tableBanners: [],
      dialogShow: false,
      bannerList: [], // 显示图片组件的容器
      ifEdit: false, // 是否是编辑
      EditId: '', // 正在编辑的id
      EditBannerId: '', // 正在海报的id
      num: 1, // 海报的排序
      form: {},

      ifNeedGoodsLink: false, // 是否需要启用关联商品模式  false 不关联  true 关联
      needGoodsId: '', // 需要关联商品的id
      selectLoading: false, // 关联select loading
      selectSearchOptions: [], // 筛选列表的数据
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getBanners();
    },
    // 获取用户banner
    async getBanners() {
      const { data } = await this.$api.getBanners();
      // 这里处理下banner的数据
      // let tableBanners = []
      Array.isArray(data) &&
        data.map((item, index) => {
          item.order = index + 1;
        });
      this.tableBanners = data;
    },
    async handleDel(event, { bannerId }) {
      const result = await this.$confirm('是否确认删除该轮播图', '温馨提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消',
      }).catch((action) => {
        console.log(action);
        return;
      });
      if (!result) return;
      // 处理删除逻辑
      await this.$api.delBannerById({ bannerId });
      this.$notify({ title: '删除轮播成功', type: 'success' });
      this.getBanners();
    },
    imageSuccess(list) {
      this.bannerList = list;
    },
    handleAdd() {
      this.ifEdit = false;
      this.dialogShow = true;
    },
    handleEdit(event, row) {
      console.log(row);
      this.bannerList = [
        {
          url: row.bannerPic,
        },
      ];

      if (row.productId) {
        this.needGoodsId = row.productId;
        this.ifNeedGoodsLink = !!row.productId;
      }

      this.EditBannerId = row.bannerId;
      this.EditId = row.id;
      this.ifEdit = true;
      this.dialogShow = true;
    },
    // 新增海报
    async handleAddBanner() {
      const {
        bannerList,
        ifEdit,
        EditId,
        EditBannerId,
        ifNeedGoodsLink,
        needGoodsId,
      } = this.$data;
      if (bannerList.length === 0) {
        this.$message({
          type: 'warning',
          message: `请上传banner图片`,
        });
        return;
      }
      const bannerPic = bannerList[0].url;
      const params = {
        bannerPic,
        merchantId: this.$store.getters.customerId,
      };

      // 这里判断下用户是不是使用了关联商品模式
      // 如果使用了 判断下商品id是否已经填了
      if (ifNeedGoodsLink) {
        if (!needGoodsId) {
          this.$message({
            type: 'warning',
            message: `请选择您需要关联的商品`,
          });
          return;
        }
        params.productId = needGoodsId;
      }

      if (ifEdit) {
        await this.$api.setBannerById(
          Object.assign(params, { bannerId: EditBannerId, id: EditId })
        );
        this.$notify({ title: '编辑轮播成功', type: 'success' });
      } else {
        await this.$api.addBanner(params);
        this.$notify({ title: '新增轮播成功', type: 'success' });
      }

      this.getBanners();

      setTimeout(() => {
        this.resetDialog();
      });
    },
    resetDialog() {
      this.bannerList = [];
      this.dialogShow = false;
      this.ifNeedGoodsLink = false;
      this.needGoodsId = '';
      this.EditId = '';
      this.selectSearchOptions = [];
    },
    async remoteMethod(keyword) {
      if (keyword === '') {
        this.selectSearchOptions = [];
        return;
      }

      this.selectLoading = true;
      const { data, success, errMessage } = await this.$api
        .getProductDetail(keyword)
        .catch((err) => {
          this.$message({
            type: 'warning',
            message: `${err.errMessage}`,
          });
          this.selectLoading = false;
          return;
        });
      if (!success) {
        this.$message({
          type: 'warning',
          message: `${errMessage || '系统繁忙，请稍后再试'}`,
        });
        this.selectLoading = false;
        return;
      }

      if (data) {
        this.selectSearchOptions = [data];
      }
      this.selectLoading = false;
    },
  },
  components: {
    UploadImage,
  },
};
</script>
